package com.shuql.cloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.shuql.cloud.config.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @author ：shuquanliang
 * @date ：Created in 2020/4/24 11:37
 * @description：
 */
@Component
public class ValidateTokenFilter extends ZuulFilter {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 配置哪些url请求需要验证token
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
//        RequestContext requestContext = RequestContext.getCurrentContext();
//        HttpServletRequest request = requestContext.getRequest();
//        String url = request.getRequestURI();
//        String requestMethod = requestContext.getRequest().getMethod();
//        if (url.startsWith("/accounts")) {
//            if (url.startsWith("/accounts/demo")) {
//                return false;
//            }
//            if ("POST".equals(requestMethod)) {
//                return false;
//            }
//            return true;
//        }
//
//        if (url.startsWith("/auth/oauth/") || url.startsWith("/auth/login")) {
//            return false;
//        }
//
//        if (url.startsWith("/statistics") || url.startsWith("/notification")) {
//            return true;
//        }

        return true;
    }

    @Override
    public Object run() throws ZuulException {
//        RequestContext requestContext = RequestContext.getCurrentContext();
//        String token = requestContext.getRequest().getHeader("Authorization");
//        if (StringUtils.isBlank(token)) {
//            throw new ZuulException(new Throwable("not found token"), HttpStatus.UNAUTHORIZED.value(), "not found token");
//        }
//
//        token = token.replace("Bearer ", "");
//        String creds = String.format("%s:%s", securityProperties.getClientId(), securityProperties.getClientSecret());
//        HttpHeaders headers = new HttpHeaders();
//        try {
//            headers.add("Authorization", "Basic " + new String(Base64Utils.encode(creds.getBytes("UTF-8"))));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        headers.set("Accept", "application/json");
//
//        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
//        map.add("token", token);
//        map.add("token_type_hint", "access_token");
//
//        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
//        Map<String, Object> resultMap = restTemplate.postForEntity(securityProperties.getAuthServiceUrl(), request, Map.class).getBody();
//        Boolean active = (Boolean) resultMap.get("active");
//        if (active == null || !active) {
//            throw new ZuulException(new Throwable("token inactive"), HttpStatus.UNAUTHORIZED.value(), "token inactive");
//        }
//
//        String username = (String) resultMap.get("user_name");
//        if (StringUtils.isBlank(username)) {
//            throw new ZuulException(new Throwable("username is empty"), HttpStatus.UNAUTHORIZED.value(), "username is empty");
//        }

        return null;
    }

}
